
package network;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

/**
 * 网络工具类
 *
 */
public class NetUtils {

    private static final String TAG = "NetUtils";

    public static final int CONNECTION_TYPE_NULL = 0;
    public static final int CONNECTION_TYPE_MOBILE = 1;
    public static final int CONNECTION_TYPE_WIFI = 2;

    /**
     * 获取当前网络类型
     *
     * @param context
     * @return
     */
    public static int getConnectionType(Context context) {

        ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = conMan.getActiveNetworkInfo();

        if (networkInfo == null) {
            return CONNECTION_TYPE_NULL;
        } else {
            if (networkInfo.getState() != NetworkInfo.State.CONNECTED) {
                return CONNECTION_TYPE_NULL;
            }

            int type = networkInfo.getType();
            if (type == ConnectivityManager.TYPE_WIFI) {
                return CONNECTION_TYPE_WIFI;
            } else if (type == ConnectivityManager.TYPE_MOBILE) {
                return CONNECTION_TYPE_MOBILE;
            } else {
                return CONNECTION_TYPE_WIFI;
            }
        }
    }

    /**
     * 获取网络名称
     *
     * @param context
     * @return
     */
    public static String getConnectionTypeName(Context context) {

        ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = conMan.getActiveNetworkInfo();

        if (networkInfo == null) {
            return null;
        } else {

            if (networkInfo.getState() != NetworkInfo.State.CONNECTED) {
                return null;
            }

            int type = networkInfo.getType();

            if (type == ConnectivityManager.TYPE_WIFI) {
                return networkInfo.getTypeName();
            } else if (type == ConnectivityManager.TYPE_MOBILE) {
                String netType = networkInfo.getExtraInfo();
                netType = netType + "_" + networkInfo.getSubtypeName();
                return netType;
            } else {
                return null;
            }
        }
    }

    /**
     * 是否已连接wifi
     *
     * @param context
     * @return
     */
    public static boolean isConnectWifi(Context context) {

        return getConnectionType(context) == CONNECTION_TYPE_WIFI;
    }

    /**
     * 是否已连接移动网络
     *
     * @param context
     * @return
     */
    public static boolean isConnectMobile(Context context) {

        return getConnectionType(context) == CONNECTION_TYPE_MOBILE;
    }

    /**
     * 是否是未连接网络
     *
     * @param context
     * @return
     */
    public static boolean isConnectNull(Context context) {

        return getConnectionType(context) == CONNECTION_TYPE_NULL;
    }

    /**
     * InputStream转换成string类型
     *
     * @param is
     * @return
     * @throws IOException
     */
    public static String convertStreamToString(InputStream is) {
        
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine() method. We
         * iterate until the BufferedReader return null which means there's no more data to read.
         * Each line will appended to a StringBuilder and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;

        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }

    /**
     * 重新组织url参数
     *
     * @param url    域名
     * @param params 要组织的参数
     * @return
     */
    public static String organizeUrlParam(String url, HashMap<String, String> params) {

        String paramStr = "";

        try {

            Iterator<Entry<String, String>> iter = params.entrySet().iterator();

            while (iter.hasNext()) {

                Entry<String, String> entry = iter.next();
                String key = entry.getKey();
                key = URLEncoder.encode(key, "UTF-8");
                String val = entry.getValue();
                if (!TextUtils.isEmpty(val)) {
                    val = URLEncoder.encode(val, "UTF-8");
                }

                paramStr += paramStr = "&" + key + "=" + val;
            }
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }

        if (!TextUtils.isEmpty(paramStr)) {

            if (!url.contains("?")) {
                paramStr = paramStr.replaceFirst("&", "?");
            }

            url += paramStr;
        }

        Log.d(TAG, "organizeUrl " + url);

        return url;
    }

    /**
     * 组织url参数，针对批量，key相同，value不同的情况
     *
     * @param url
     * @param key
     * @param values
     * @return
     */
    public static String organizeUrlParam(String url, String key, List<String> values) {

        String paramStr = "";
        try {
            key = URLEncoder.encode(key, "UTF-8");
            for (int i = 0; i < values.size(); i++) {
                String val = values.get(i);
                val = URLEncoder.encode(val, "UTF-8");
                paramStr += paramStr = "&" + key + "=" + val;
            }
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }

        if (!TextUtils.isEmpty(paramStr)) {

            if (!url.contains("?")) {
                paramStr = paramStr.replaceFirst("&", "?");
            }

            url += paramStr;
        }

        Log.d(TAG, "organizeUrl " + url);

        return url;
    }
}
